﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.Authentication;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using Cms.Web.Framework.Controls;

namespace Cms.Web.Framework.Plugins
{
    public class Login : BaseTemplatedPlugin
    {
        // Template controls
        private TextBox txtPassword;
        private TextBox txtUsername;
        private LocalizedPluginLiteral lplWrongCredentialsErrorMessage;
        private LocalizedPluginLiteral lplNoActiveMembershipErrorMessage;

        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                txtUsername = (TextBox)FindControl("txtUsername");
                txtPassword = (TextBox)FindControl("txtPassword");
                lplWrongCredentialsErrorMessage = (LocalizedPluginLiteral)FindControl("lplWrongCredentialsErrorMessage");
                lplNoActiveMembershipErrorMessage = (LocalizedPluginLiteral)FindControl("lplNoActiveMembershipErrorMessage");
                var btnLogin = (Button)FindControl("btnLogin");
                var lbLogin = (LinkButton)FindControl("lbLogin");
                if (btnLogin != null)
                    btnLogin.Click += btnLogin_Click;
                if (lbLogin != null)
                    lbLogin.Click += lbLogin_Click;
            }
            catch (Exception ex)
            {
                Logging.LogError("Login", ex);
                Controls.Clear();
            }
        }
        
        private void btnLogin_Click(object sender, EventArgs e)
        {
            Authenticate();
        }

        private void lbLogin_Click(object sender, EventArgs e)
        {
            Authenticate();
        }

        private void Authenticate()
        {
            IUserRepository userRepository = new UserRepository();
            User user = userRepository.GetUser(txtUsername.Text, txtPassword.Text);
            if (user == null)
            {
                AddError(lplWrongCredentialsErrorMessage.Text, "Login");
                return;
            }
            Cms.Domain.Membership membership = user.Memberships.FirstOrDefault(m => m.IsActive());
            if (membership == null)
            {
                AddError(lplNoActiveMembershipErrorMessage.Text, "Login");
                return;
            }
            AuthenticatedUser authenticatedUser = HttpContext.Current.User.Identity.IsAuthenticated
                                                      ? Conversion.ToAuthenticatedUser(Page.User.Identity.Name)
                                                      : new AuthenticatedUser();
            authenticatedUser.UserID = user.ID;
            string username = Conversion.ToCompressedString(authenticatedUser);
            FormsAuthentication.SetAuthCookie(username, false);
            Response.Redirect(membership.UserGroup.GetStartPageUrl());
        }
    }
}